package com.d.client.interceptor;

import com.d.client.DingClient;
import com.d.client.dto.DingAppAccessTokenDto;
import com.d.common.utils.RedisUtil;
import com.dtflys.forest.exceptions.ForestRuntimeException;
import com.dtflys.forest.http.ForestRequest;
import com.dtflys.forest.http.ForestResponse;
import com.dtflys.forest.interceptor.Interceptor;
import com.dtflys.forest.utils.ForestDataType;
import com.dtflys.forest.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class DingInterceptor implements Interceptor {

    @Value("${forest.variables.dingAppKey}")
    String dingAppKey;
    @Value("${forest.variables.dingAppSecret}")
    String dingAppSecret;
    @Autowired
    private DingClient dingClient;

    private String REDIS_TOKEN_CACHE_KEY = "ding_token_" + dingAppKey;

    /**
     * 该方法在请求发送之前被调用, 若返回false则不会继续发送请求
     */
    @Override
    public boolean beforeExecute(ForestRequest request) {

        request.setDataType(ForestDataType.JSON);
        request.setContentType("application/json");
        request.setCharset("UTF-8");

        try {
            String uri = request.getUrl();
            if (uri.indexOf("/accessToken") == -1) {
//                log.info("-------------body:"+request.getBody().get(0).toString());
                String token;
                if (StringUtils.isEmpty(RedisUtil.getJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey))) {
                    DingAppAccessTokenDto tokenDto = dingClient.getAppToken(dingAppKey, dingAppSecret);
                    token = tokenDto.getAccessToken();
                    RedisUtil.setJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey, tokenDto.getAccessToken(), tokenDto.getExpireIn().intValue());
                } else {
                    token = RedisUtil.getJedisVal(REDIS_TOKEN_CACHE_KEY + dingAppKey);
                }
                request.addHeader("x-acs-dingtalk-access-token", token);
                log.info(token+"-------------------------------------");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }

    /**
     * 请求发送失败时被调用
     *
     * @param e
     * @param forestRequest
     * @param forestResponse
     */
    @Override
    public void onError(ForestRuntimeException e, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.info("url:【{}】,result:【{}】", forestRequest.getUrl(), forestResponse.getContent());
    }

    /**
     * 请求成功调用(微信端错误异常统一处理)
     *
     * @param o
     * @param forestRequest
     * @param forestResponse
     */
    @Override
    public void onSuccess(Object o, ForestRequest forestRequest, ForestResponse forestResponse) {
        log.info("url:【{}】,result:【{}】", forestRequest.getUrl(), forestResponse.getContent());
    }

}
